<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" width="50">
			</el-table-column>
			<el-table-column prop="name" label="服务名称" width="140" sortable>
			</el-table-column>
      <el-table-column prop="costprice" label="市场价" width="80" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="零售价" width="80" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="80" sortable>
      </el-table-column>
      <el-table-column prop="state" label="服务状态" width="60" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">上架</span>
          <span v-else style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="110" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="110" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="录入时间" width="110" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 批量删除和分页栏 -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!-- 编辑界面 -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="零售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="服务图片" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.productDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
			  // 1.分页查询的模型数据
        products: [],
        totals: 0,
        listLoading: false,
        currentPage: 1,
        pageSize: 5,

        // 2.高级查询的模型数据
        keyword: '',

        // 3.批量删除
        sels: [],//列表选中列

        // 4.添加和修改的模型数据
				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
        title: '',
				saveFormRules: {
          name: [
            { required: true, message: '请输入服务名称', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					name: '',
          costprice: 0,
          saleprice: 0,
          resources: '',
          productDetail:{
            intro: '',
            orderNotice: ''
          }
				},

        // 5.文件上传列表 - 资源resources
        fileList:[],
			}
		},
		methods: {
      //1.获取服务列表
      getProducts() {
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/product", para).then(res => {
          this.products = res.data.data;
          this.totals = res.data.totals;
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("网络繁忙，请稍后重试！");
        })
      },

      // 2.点击实现分页查询方法
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getProducts();
      },

      // 3.高级查询的方法
      keywordQuery() {
        // 将当前页更置为1，防止在其他页查询时出现bug
        this.currentPage = 1;
        this.getProducts();
      },

      // 4.删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => { // 点击确认
          this.listLoading = true; // 打开加载框
          this.$http.delete("/product/" + row.id).then(res => {
            if (res.data.success) {
              // 当删除掉当前页的最后一条数据后，跳转到前一页，如果当前页是最后一页，删除最后一条数据后，还是停留在当前页
              let pageTotals = Math.ceil(this.totals / this.pageSize);
              if (this.currentPage == pageTotals && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
                this.currentPage = this.currentPage - 1;
              }
              this.getProducts();
            } else {
              this.$message.error("系统繁忙，请稍后重试！");
            }
            this.listLoading = false; // 关闭加载框
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试！");
          })
        }).catch(() => { // 点击取消
        });
      },

      // 5.选中后数组改变
      selsChange: function (sels) {
        this.sels = sels;
      },

      // 6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/product", ids).then(res => {
            if (res.data.success) {
              this.currentPage = 1;
              this.getProducts();
            } else {
              this.$message.error("系统繁忙，请稍后重试！");
            }
            this.listLoading = false; // 关闭加载框
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试！");
          });
        }).catch(() => { // 点击取消
        });
      },

      // 7.点击编辑按钮弹出对话框
      handleSave: function (index, row) {
        this.title = "修改";
        this.saveForm = Object.assign({}, row);
        //处理fileList - 点击修改能够回显图片
        this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
        if(this.saveForm.resources){
          // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
            this.fileList.push({"url":"http://123.207.27.208" + item});
          }
        }
        this.saveFormVisible = true;
      },

      // 8.点击新增按钮弹出对话框
      handleAdd: function () {
        this.title = "新增";
        this.saveForm = {
          id: null,
          name: '',
          costprice: 0,
          saleprice: 0,
          resources: '',
          productDetail:{
            intro: '',
            orderNotice: ''
          }
        }
        //清空fileList的数据
        this.fileList = []
        this.saveFormVisible = true;
      },

      // 9.添加和修改的方法
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              this.$http.put("/product",this.saveForm).then(res => {
                if (res.data.success) {
                  this.getProducts();
                } else {
                  this.$message.error("系统繁忙，请稍后重试！");
                }
                this.listLoading = false; // 关闭加载框
                this.saveLoading = false;
              }).catch(res => {
                this.$message.error("系统繁忙，请稍后重试！");
              });
              // 关闭对话框
              this.saveFormVisible = false;
            });
          }
        });
      },

      // 10.文件上传的业务逻辑
      handleSuccess(response, file, fileList){
        // 对resources处理，添加到数据库
        if (this.saveForm.resources) {
          this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
        } else {
          this.saveForm.resources = response.resultObj;
        }
        // 对fileList处理，前端显示图片
        this.fileList = [];
        if (this.saveForm.resources) {
          var arr = this.saveForm.resources.split(",");
          for (var i=0;i<arr.length;i++) {
            this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
          }
        }
      },

      // 11.文件删除的业务逻辑
      handleRemove(file, fileList){
        //1.调用删除接口删除图片
        var path = file.url.substring(file.url.indexOf("/group"));
        this.$http.delete("/fastDfs?path="+path).then(res=>{
          if(res.data.success){
            this.$message.success("删除成功")
          }else{
            this.$message.success("删除失败")
          }
        })
        //2.对resource做处理
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i];
            if(path==item){//找到了删除的图片
              arr.splice(i,1);//删除指定的图片
            }
          }
          this.saveForm.resources = arr.join(",")
        }
        //3.对fileList的处理 - 前端显示图片的
        this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i];
            this.fileList.push({"url":"http://123.207.27.208" + item});
          }
        }
      },

      // 12.上架
      onsale() {
        var ids = this.sels.map(item => item.id);
        if (!this.sels || this.sels.length < 1) {
          this.$message.error("没有选择需要上架的商品！");
          return;
        }
        this.$confirm('确认要上架吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post("/product/onsale", ids).then(res => {
            if (res.data.success) {
              this.getProducts();
              this.$message.success("上架成功！");
            } else {
              this.$message.error("上架失败！");
            }
            this.listLoading = false; // 关闭加载框
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试！");
          });
        }).catch(() => { // 点击取消
        });
      },

      // 13.下架
      offsale() {
        var ids = this.sels.map(item => item.id);
        if (!this.sels || this.sels.length < 1) {
          this.$message.error("没有选择需要下架的商品！");
          return;
        }
        this.$confirm('确认要下架吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post("/product/offsale", ids).then(res => {
            if (res.data.success) {
              this.getProducts();
              this.$message.success("下架成功！");
            } else {
              this.$message.error("上下架失败！");
            }
            this.listLoading = false; // 关闭加载框
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试！");
          });
        }).catch(() => { // 点击取消
        });
      }

    },
		mounted() {
			this.getProducts();
		}
	}
</script>

<style scoped>

</style>